package com.sap.mobile.maf.samples.android.mafprovisioningsample;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;

import android.R.drawable;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;

import com.sap.maf.tools.logon.logonapi.LogonContext;
import com.sap.maf.tools.logon.logonmanager.LogonManager;
import com.sap.maf.tools.logon.logonmanager.LogonManager.LogonManagerException;
import com.sap.maf.uicontrols.MAFSkinManager;
import com.sap.maf.uicontrols.MAFUIFactory;
import com.sap.maf.uicontrols.view.MAFActionBar;
import com.sap.maf.uicontrols.view.MAFActionBarItem;
import com.sap.maf.uicontrols.view.MAFToast;
import com.sap.maf.utilities.logger.MAFLogger;
import com.sap.mobile.lib.sdmconnectivity.ISDMNetListener;
import com.sap.mobile.lib.sdmconnectivity.ISDMRequest;
import com.sap.mobile.lib.sdmconnectivity.ISDMRequestStateElement;
import com.sap.mobile.lib.sdmconnectivity.ISDMResponse;
import com.sybase.mo.MessagingClientException;
import com.sybase.mobile.lib.client.ODPAppSettings;
import com.sybase.mobile.lib.client.ODPClientConnection;
import com.sybase.mobile.lib.client.ODPClientListeners.IODPConfigurationChangeListener;
import com.sybase.mobile.lib.client.ODPException;
import com.sybase.mobile.lib.client.ODPUserManager;

/**
 * Sample application to show the usage of the MAF Logon API. The purpose of the
 * API is to attach a reusable logon screen to the application conveniently. To
 * use it you have to implement LogonContextListener which has 4 callback
 * methods.<br>
 * OnLogonFinished: when all of the supplied credentials were correct, this
 * callback is fired and usually the application logic is called<br>
 * onLogonCanceled: the cancel button was pressed on the logon screen, meaning
 * the user wants to exit the application<br>
 * onLogonContextUpdated: the login button was pressed on the logon screen, so a
 * good use case would be to show a process dialog and start the onboarding
 * process<br>
 * onLogonFailed: the onboarding process failed, so we should let the user know
 * about this and handle the error (errorcode)<br>
 * 
 */
public class ApplicationActivity extends Activity implements ISDMNetListener, IODPConfigurationChangeListener {
	Intent returnIntent = new Intent();
	private final String TAG = "LogonProvisionActivity";
	private boolean isSampleData = false;
	private static Context ctx;
	private static Activity act;
	private static int xmlVer=1;
	private static boolean isRegistered=false;
	
	/**
	 * Called when the activity is first created. Inflate the logon screen, then
	 * inflate our main screen above the footer and set it invisible.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		act=this;
		ctx=this;
		super.onCreate(savedInstanceState);
		setResult(LockScreenActivity.applicationRequestCode, returnIntent);

		try {
			createUI();
		} catch (MessagingClientException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
try {
			doApplicationLogic();
		} catch (LogonManagerException e) {
			MAFLogger.e(TAG, e.getMessage());
		}
		CheckBox ckb = (CheckBox) findViewById(R.id.main_screen_checkbox);
		ckb.setChecked(isRegistered);
	}

	private void createUI() throws MessagingClientException {
		setContentView(R.layout.main);
		final SharedPreferences localPrefs = getSharedPreferences(
				getPackageName() + "_preferences", MODE_PRIVATE);
		final String styleName = localPrefs.getString("themeID", "Default");
		try {
			MAFSkinManager.getInstance(this).setActiveStyle(styleName);
		} catch (IllegalArgumentException e) {
			
		}

		MAFActionBar aBar = (MAFActionBar) findViewById(R.id.main_screen_actioin_bar);

		LogoutActionBarItem setABI = new LogoutActionBarItem(1,
				drawable.ic_menu_close_clear_cancel,
				R.string.main_screen_button_label_logout);
		aBar.addDefaultAction(setABI);

		MAFUIFactory.getInstance().reskinUI(this);

		try {
			if (ODPUserManager.getInstance().isUserRegistered()) {
				isSampleData = false;
			} else {
				isSampleData = true;
			}
		} catch (ODPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Application logic with logout button.
	 * 
	 * @param logonContext
	 * @throws LogonManagerException
	 */
	private void doApplicationLogic() throws LogonManagerException {
		try {
			LogonContext logonContext = LogonManager.getLogonContext(this);
		} catch (MessagingClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Button regButton = (Button) findViewById(R.id.main_screen_register_button);

		regButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				registerForProvisioning("com.sap.maf.test.adr.provision");
				
				
			}
		});

	}

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.preferences:
			startActivityForResult(new Intent(this,
					SamplePreferenceActivity.class),
					LockScreenActivity.preferenceRequestCode);
			break;
		default:
			return super.onOptionsItemSelected(item);
		}
		return true;
	}

	private class LogoutActionBarItem extends MAFActionBarItem {

		public LogoutActionBarItem(int id, int iconId, int textId) {
			super(id, iconId, textId);
		}

		@Override
		public void performAction() {
			returnIntent.putExtra("isLogoutStarted", true);
			finish();
		}
	}

	
	
	
	public ZipInputStream initSUPProvisioning(String customizationResource, String user, String pass) throws MessagingClientException{
		
		ODPAppSettings las = new ODPAppSettings();
		byte[] propertyMetadata = null;
		try {
			propertyMetadata = las.getCustomizationResourceBundle(
					customizationResource, user, pass);
		} catch (ODPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		ZipInputStream zipIn = new ZipInputStream(
				new ByteArrayInputStream(propertyMetadata));

		return zipIn;
	
	}
	
	public void registerForProvisioning(String appID){
		try {
			ODPClientConnection.initInstance(getApplicationContext(), appID);
			ODPClientConnection lm = null;
			lm = ODPClientConnection.getInstance();
			lm.addConfigurationChangeListener((IODPConfigurationChangeListener) this);
			
		} catch (ODPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		isRegistered=true;
		CheckBox ckb;
		ckb = (CheckBox) findViewById(R.id.main_screen_checkbox);
		ckb.setChecked(true);			
	}

	@Override
	public void onConfigurationChange(int arg0, String arg1) {
		MAFLogger.i("Configuration has changed", "Value: " + arg1);
		if (arg0 == 2903 && !arg1.equals("")) {
			
			LogonContext logonContext = null;
			try {
				try {
					logonContext = LogonManager.getLogonContext(this);
				} catch (MessagingClientException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (LogonManagerException e1) {
				MAFLogger.e(TAG, "get xml error, " + e1.getMessage());
			}
			ZipInputStream zipIn = null;
			try {
				zipIn = initSUPProvisioning(arg1, logonContext.getEndPointUser(), logonContext.getEndPointPassword());
			} catch (MessagingClientException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
				ZipEntry zipentry;
				
				while ( (zipentry = zipIn.getNextEntry()) != null ) {
					MAFLogger.i("ENDPOINTLISTENER" , zipentry.getName());
					if (zipentry.getName().equalsIgnoreCase("META-INF/MANIFEST.MF")) {
						System.out.println("Manifest found");
					}
					if (zipentry.getName().endsWith(".xml")){
						
						MAFSkinManager.getInstance(this).loadStyle("Provision v"+xmlVer , zipIn);
						MAFSkinManager.getInstance(this).setActiveStyle("Provision v"+xmlVer);
						SharedPreferences localPrefs = getSharedPreferences(
								getPackageName() + "_preferences", MODE_PRIVATE);
						Editor editor = localPrefs.edit();
						editor.putString("themeID", "Provision v"+xmlVer);
						editor.commit();
					}
				}
			} catch (IOException e) {
			}
			runOnUiThread(new Runnable() {
			    public void run() {
			    	MAFUIFactory.getInstance().reskinUI(act);
			    	MAFToast.makeText(
							ctx,
							"Provision v" + xmlVer +".xml has been set",MAFToast.LENGTH_SHORT).show();
			    	xmlVer++;
			    }
			});
			
			
		}

	}

	@Override
	public void onError(ISDMRequest arg0, ISDMResponse arg1,
			ISDMRequestStateElement arg2) {
		MAFLogger.e(TAG, "Error with request" + arg1.getStatusLine().getStatusCode());
		MAFToast.makeText(this, "Error with request!", MAFToast.LENGTH_SHORT)
				.show();
	}

	@Override
	public void onSuccess(ISDMRequest arg0, ISDMResponse arg1) {
		MAFLogger.i(TAG, "Service doc fetch succeeded: " + arg1.getStatusLine().getStatusCode());
		if (arg1.getStatusLine().getStatusCode() == 200) {
			try {
				String serviceDoc = EntityUtils.toString(arg1.getEntity()); 
				MAFLogger.i(TAG, "Service doc fetch succeeded: " + serviceDoc);
				} catch (ParseException e) {
				MAFLogger.e(TAG, "get xml error, " + e.getMessage());
			} catch (IOException e) {
				MAFLogger.e(TAG, "get xml error, " + e.getMessage());
			}
		}
	}
	
}